package com.imdroid.lite.activities;

import java.lang.reflect.Field;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKLocationManager;
import com.imdroid.lite.IMDroid;
import com.imdroid.lite.R;
import com.imdroid.lite.process.ProcessFactory;
import com.imdroid.lite.process.UserProcess;

public class MatchActivity extends BaseActivity implements SensorEventListener,
		LocationListener {
	/**
	 * The tag of the match activity
	 */
	private String TAG = "MatchActivity";
	/**
	 * The sensor manager
	 */
	private SensorManager sensorManager;
	/**
	 * The sensor of accelerometer
	 */
	private Sensor accelerometer;
	/**
	 * The maxmium tolerance
	 */
	private static final float tolerance = (float) 6;
	/**
	 * if open the sence
	 */
	private static boolean allowSence = true;
	/**
	 * The current location
	 */
	private Location currentLocation = null;
	/**
	 * The map manager
	 */
	private BMapManager bMapManager;
	private MKLocationManager locationManager;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.imdroid.lite.activities.BaseActivity#onCreate(android.os.Bundle)
	 */
	public void onCreate(Bundle bdl) {
		super.onCreate(bdl);
		setContentView(R.layout.match);
		// 注册感應器
		sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
		accelerometer = sensorManager
				.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

		// 注册location listener得到当前位置
		IMDroid app = (IMDroid) this.getApplication();
		bMapManager = app.mBMapMan;
		// 设置可以查询
		allowSence = true;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onResume()
	 */
	@SuppressWarnings("deprecation")
	protected void onResume() {
		super.onResume();
		// 注册感應器
		sensorManager.registerListener(this, accelerometer,
				SensorManager.SENSOR_ACCELEROMETER);
		Log.d(TAG, "onResume---" + bMapManager);
		// 注册百度地图管理器
		if (bMapManager != null) {
			bMapManager.start();

			locationManager = bMapManager.getLocationManager();
			// 初始化location manager
			locationManager.enableProvider(MKLocationManager.MK_GPS_PROVIDER);
			locationManager
					.enableProvider(MKLocationManager.MK_NETWORK_PROVIDER);
			locationManager.requestLocationUpdates(this);
			locationManager.setNotifyInternal(5, 2);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onPause()
	 */
	protected void onPause() {
		super.onPause();
		Log.d(TAG, "onPause...");
		// 注销感應器
		sensorManager.unregisterListener(this, accelerometer);
		// 注销百度地图管理器
		if (bMapManager != null) {
			bMapManager.stop();
		}
		locationManager.removeUpdates(this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.hardware.SensorEventListener#onAccuracyChanged(android.hardware
	 * .Sensor, int)
	 */
	public void onAccuracyChanged(Sensor sensor, int accuracy) {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.hardware.SensorEventListener#onSensorChanged(android.hardware
	 * .SensorEvent)
	 */
	public void onSensorChanged(SensorEvent event) {
		int sensorType = event.sensor.getType();
		float[] values = event.values;

		if (sensorType == Sensor.TYPE_ACCELEROMETER) {
			float motion = (values[0] > values[1] ? values[0] : values[1]);
			motion = (motion > values[2] ? motion : values[2]);
			float shock = Math.abs((float) (motion - 9.8));

			// Log.d(TAG, "start search nearby---" + allowNearby + "--"+shock);
			if (allowSence && (shock > tolerance)) {
				Log.d(TAG, "start search nearby---" + shock);
				(new FindMatchDeviceTask(this, R.string.home_match_wait_title,
						R.string.home_match_wait_text)).execute(new Object());
				// 查询期间，设置成不响应
				allowSence = false;
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.baidu.mapapi.LocationListener#onLocationChanged(android.location.
	 * Location)
	 */
	public void onLocationChanged(Location arg0) {
		if (arg0 != null) {
			Log.d(TAG,
					"Location changed:" + arg0.getLatitude() + " - "
							+ arg0.getLongitude());
			currentLocation = arg0;
		}
	}

	/**
	 * Back
	 * 
	 * @param view
	 *            the view
	 */
	public void back(View view) {
		this.finish();
	}

	/**
	 * The task of the find match device
	 * 
	 */
	private class FindMatchDeviceTask extends ProgressBarAsyncTask {
		/**
		 * The string of the server return
		 */
		private String matchString = null;

		/**
		 * The constructor
		 * 
		 * @param context
		 *            the application context
		 * @param titleText
		 *            the title text
		 * @param messageText
		 *            the message text
		 */
		public FindMatchDeviceTask(BaseActivity context, int titleText,
				int messageText) {
			super(context, titleText, messageText);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see com.imdroid.lite.activities.BaseActivity.ProgressBarAsyncTask#
		 * doInBackground(java.lang.Object[])
		 */
		protected Exception doInBackground(Object... params) {

			// 取得本地位置
			int i = 0;
			while (currentLocation == null) {
				try {
					if (i >= 21)
						return new Exception(
								context.getString(R.string.home_match_fail_no_gps));
					Thread.sleep(1 * 1000);
					++i;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// 获取最近的正在配对的车机
			try {
				UserProcess process = (UserProcess) ProcessFactory
						.getProcess(UserProcess.class);

				matchString = process.getCloseMatchDevice(
						currentLocation.getLatitude(),
						currentLocation.getLongitude());
			} catch (Exception e) {
				return e;
			}
			return null;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see com.imdroid.lite.activities.BaseActivity.ProgressBarAsyncTask#
		 * onPostExecute(java.lang.Exception)
		 */
		protected void onPostExecute(Exception result) {
			super.onPostExecute(result);
			// 如果有错误
			if (result != null) {
				Toast.makeText(context, result.getMessage(), Toast.LENGTH_SHORT)
						.show();
				allowSence = true;
				return;
			}
			// 从返回字串中解析user_id和nick_name
			String[] item = matchString.split("&&");
			final int user_id = Integer.parseInt(item[0]);
			final String nick_name = item[1];
			// 弹出对话框
			AlertDialog.Builder buidler = new AlertDialog.Builder(context);
			String text = context.getString(R.string.home_match_device);
			text = text.replace("%1%", nick_name);
			buidler.setIcon(android.R.drawable.ic_dialog_info);
			buidler.setTitle(text);

			final EditText edit = new EditText(context);
			edit.setGravity(Gravity.CENTER);
			final FrameLayout frameLayout = new FrameLayout(context);
			frameLayout.addView(edit);
			buidler.setView(frameLayout);
			// 确定
			buidler.setPositiveButton(context.getString(R.string.home_confirm),
					new OnClickListener() {
						/*
						 * (non-Javadoc)
						 * 
						 * @see
						 * android.content.DialogInterface.OnClickListener#onClick
						 * (android.content.DialogInterface, int)
						 */
						public void onClick(DialogInterface dialog, int which) {
							String matchCode = edit.getText().toString();
							if (matchCode == null || matchCode.length() <= 0) {
								context.showAlert(context
										.getString(R.string.home_match_no_code));
								// 不退出对话框
								try {
									Field field = dialog.getClass()
											.getSuperclass()
											.getDeclaredField("mShowing");
									field.setAccessible(true);
									field.set(dialog, false);
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								return;
							}
							// 进行匹配
							(new MatchDeviceTask(context,
									R.string.home_match_wait_title,
									R.string.home_match_wait_text)).execute(
									user_id + "", matchCode);

						}
					});
			// 取消
			buidler.setNegativeButton(context.getString(R.string.home_cancel),
					new OnClickListener() {
						/*
						 * (non-Javadoc)
						 * 
						 * @see
						 * android.content.DialogInterface.OnClickListener#onClick
						 * (android.content.DialogInterface, int)
						 */
						public void onClick(DialogInterface dialog, int which) {
							allowSence = true;
						}
					});
			buidler.show();
		}
	}

	/**
	 * The task of the match device
	 * 
	 */
	private class MatchDeviceTask extends ProgressBarAsyncTask {
		private boolean success = false;

		/**
		 * The constructor
		 * 
		 * @param context
		 *            the application context
		 * @param titleText
		 *            the title text
		 * @param messageText
		 *            the message text
		 */
		public MatchDeviceTask(BaseActivity context, int titleText,
				int messageText) {
			super(context, titleText, messageText);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see com.imdroid.lite.activities.BaseActivity.ProgressBarAsyncTask#
		 * doInBackground(java.lang.Object[])
		 */
		protected Exception doInBackground(Object... params) {
			super.doInBackground(params);
			try {
				UserProcess process = (UserProcess) ProcessFactory
						.getProcess(UserProcess.class);
				success = process.matchDevice(Integer
						.parseInt((String) params[0]), IMDroid.getUser()
						.getUser_id(), (String) params[1]);
			} catch (Exception e) {
				return e;
			}
			return null;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see com.imdroid.lite.activities.BaseActivity.ProgressBarAsyncTask#
		 * onPostExecute(java.lang.Exception)
		 */
		protected void onPostExecute(Exception result) {
			super.onPostExecute(result);
			// 如果有错误
			if (result != null) {
				Toast.makeText(context, result.getMessage(), Toast.LENGTH_LONG)
						.show();
				allowSence = true;
				return;
			}
			int messageId = success ? R.string.home_match_ok
					: R.string.home_match_not_ok;
			Log.d(TAG, "Finish---------" + success);

			AlertDialog.Builder buidler = new AlertDialog.Builder(
					MatchActivity.this);
			buidler.setTitle(R.string.home_version_title);
			buidler.setMessage(messageId);

			buidler.setPositiveButton("Ok", new OnClickListener() {
				public void onClick(DialogInterface arg0, int arg1) {
					context.finish();
				}
			});
			buidler.show();

		}
	}
}
